package com.example.it_com.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.example.it_com.common.Result;
import com.example.it_com.entity.User;
import com.example.it_com.mapper.UserMapper;
import com.example.it_com.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/admin")
@Slf4j
public class AdminController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;

    //删除用户
    @DeleteMapping("/deleteuser")
    public Result<String> deleteUser(Integer userId) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(User::getUserId, userId);
        User user = userService.getOne(queryWrapper);

        log.info(userId.toString());
       // userService.removeById(user);
        userService.remove(queryWrapper);
        return Result.success("", "删除成功");
    }

    //修改用户密码
    @PostMapping("/changepasswd")
    public Result<String> changeUserPasswd(Integer userId,String newPasswd) {
        LambdaUpdateWrapper<User> queryWrapper = new LambdaUpdateWrapper<>();

        queryWrapper.eq(User::getUserId, userId);
        User user = userService.getOne(queryWrapper);
        user.setPassWord(newPasswd);

        log.info(userId.toString());
        userMapper.update(user,queryWrapper);
        return Result.success("", "更改用户密码成功");
    }

    //修改用户状态 0正常 1封禁
    @PostMapping("/changeustate")
    public Result<String> changeUserState(Integer userId,Integer newState) {
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();

        updateWrapper.eq(User::getUserId, userId);
        User user = userService.getOne(updateWrapper);
        user.setStatus(newState);

        log.info(userId.toString());
        userMapper.update(user,updateWrapper);
        return Result.success("", "更改用户状态成功");
    }

    //获取全部用户
    @PostMapping("/getalluser")
    public Result<List<User>> getAllUser() {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getStatus, 0);

        List<User> userList = userService.list(queryWrapper);

        log.info("查询到的用户列表: {}", userList.toString());
        return Result.success(userList, "获取全部用户成功");
    }



}
